package util;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class JavaMailUtil {

    /**
     * 发送邮件
     * @param to 收件人
     * @param content 邮件内容
     * @param title 邮件标题
     */
    public static boolean sendEmail(String to,String content,String title){
        boolean result = false;
        try{
            /**
             * 1.建立连接对象，连接到服务器
             */
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");//协议
            props.setProperty("mail.smtp.host", "smtp.qq.com");//主机名
            props.setProperty("mail.smtp.port", "25");//端口号
            props.setProperty("mail.smtp.auth", "true");//是否开启权限控制
            props.setProperty("mail.debug", "true");//是否打印发送时的信息

            Session session = Session.getInstance(props);

            /**
             * 2.创建邮件对象
             */
            Message msg = new MimeMessage(session);
            //邮件发件人
            msg.setFrom(new InternetAddress("2272031885@qq.com","地表最强demo","utf-8"));
            //邮件标题
            msg.setSubject(title);

            //设置邮件内容
            msg.setContent(content, "text/html;charset=UTF-8");

            //设置邮件收件人
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to,"尊敬的用户","utf-8"));

            /**
             * 3.创建Transport对象，发送邮件
             */
            Transport trans = session.getTransport();
            //连接服务器
            trans.connect("2272031885@qq.com","bukrhsomqrumebbc");
            //发送邮件
            trans.sendMessage(msg, msg.getAllRecipients());
            //关闭连接
            trans.close();
            result = true;
        } catch (Exception ex){
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return result;
    }

}
